package com.cpit.platform.common.utils;



import java.lang.reflect.Method;

import org.apache.commons.lang3.StringUtils;
/**
 * JavaBean 反射处理
 * @author cxw
 *
 */
public class BeanUtil {
	public static Object getBeanFieldValue(Object bean, String property) {
		try {
			Method methodGet = bean.getClass().getMethod(getBeanMethod("get", property));
			return methodGet.invoke(bean);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	public static void setBeanFieldValue(Object bean, String property, Object v) {
		String name = getBeanMethod("set", property);
		try {
			Method methodSet = null;
			if (v == null) {
				Method[] methods = bean.getClass().getMethods();
				for (Method m : methods) {
					if (name.equals(m.getName())) {
						methodSet = m;
						break;
					}
				}
			} else {
				methodSet = bean.getClass().getMethod(name, v.getClass());
			}
			if (methodSet != null) {
				methodSet.invoke(bean, v);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String getBeanMethod(String op, String property){
		boolean captilize = true;
		//① 属性名对应的存取方法为 get/set 加上首字母大写的属性名
		//②如果属性名的第二个字母是大写，则它的存取方法是 set/get 加上属性原名
		if (property.length()>=2){
			//按JavaBean规范
			char c = property.charAt(1);
			if (c>='A' && c<='Z'){
				captilize = false;
			}
		}
		String propertyName = property;
		if (captilize){
			propertyName = StringUtils.capitalize(property);			
		}
		return op+propertyName;
	}
	
	public static String getStringIdentifyNull(Object obj) {
		if(obj == null)
			return "";
		else 
			return obj.toString();
	}

}
